import json
import os
import random

from base.utils.StringUtil import StringUtil
from database.IDataBase import IDataBase
from database.mydatabase import SqliteDataBase
from setting import BOOK_PATH


class BookInfo:
    def __init__(self, book_info_dict: dict):
        self.content = ''

        self.title = book_info_dict['title']
        self.src_title = book_info_dict.get('src_title', None)
        self.book_name = book_info_dict.get('book_name', None)
        self.author = book_info_dict.get('author', None)
        self.score = book_info_dict.get('score', None)
        self.eval_number = book_info_dict.get('eval_number', None)
        self.cover_url = book_info_dict.get('cover_url', None)
        self.tags = book_info_dict.get('tags', None)
        self.book_intro = book_info_dict.get('book_intro', None)
        self.author_intro = book_info_dict.get('author_intro', None)
        self.download_url = book_info_dict.get('download_url', None)
        self.categorys = book_info_dict.get('categorys', None)
        self.zhihu = book_info_dict.get('zhihu', 0)
        self.bilibili = book_info_dict.get('bilibili', 0)
        self.jianshu = book_info_dict.get('jianshu', 0)
        self.csdn = book_info_dict.get('csdn', 0)
        self.cnblogs = book_info_dict.get('cnblogs', 0)
        self.xxurls = book_info_dict.get('xxurls', 0)
        self.juejin = book_info_dict.get('juejin', 0)
        self.imooc = book_info_dict.get('imooc', 0)
        self.oschina = book_info_dict.get('oschina', 0)
        self.sf = book_info_dict.get('sf', 0)
        self.weibo = book_info_dict.get('weibo', 0)
        self.blogger = book_info_dict.get('blogger', 0)
        self.lofter = book_info_dict.get('lofter', 0)
        self.cto51 = book_info_dict.get('cto51', 0)
        self.chinaunix = book_info_dict.get('chinaunix', 0)
        self.solidot = book_info_dict.get('solidot', 0)
        self.doc360 = book_info_dict.get('doc360', 0)

    def get_article_title(self):
        article_title = '《' + self.title + '》 分享下载'
        return article_title

    def get_book_path(self):
        category_list = self.get_category_list()
        if len(category_list) > 0:
            book_path = BOOK_PATH
            for category in category_list:
                book_path += '/' + category
            book_path += '/' + self.book_name
            return os.path.abspath(book_path)

    def to_string(self):
        return str(self.book_info_dict)

    def get_tag_list(self) -> list:
        tag_list = []
        if self.tags is not None:
            tag_list = self.tags.split("##")
        return tag_list

    def get_category_list(self) -> list:
        category_list = []
        if self.categorys is not None:
            category_list = self.categorys.split("##")
        return category_list

    def get_book_info_dict(self):
        book_info_dict = {
            'title': self.title,
            'src_title': self.src_title,
            'book_name': self.book_name,
            'author': self.author,
            'score': self.score,
            'eval_number': self.eval_number,
            'cover_url': self.cover_url,
            'tags': self.tags,
            'book_intro': self.book_intro,
            'author_intro': self.author_intro,
            'download_url': self.download_url,
            'categorys': self.categorys,
            'zhihu': self.zhihu,
            'bilibili': self.bilibili,
            'jianshu': self.jianshu,
            'csdn': self.csdn,
            'cnblogs': self.cnblogs,
            'xxurls': self.xxurls,
            'juejin': self.juejin,
            'imooc': self.imooc,
            'oschina': self.oschina,
            'sf': self.sf,
            'weibo': self.weibo,
            'blogger': self.blogger,
            'lofter': self.lofter,
            'cto51': self.cto51,
            'chinaunix': self.chinaunix,
            'solidot': self.solidot,
            'doc360': self.doc360,
        }
        return book_info_dict

    def save_book_json(self, path: str):
        with open(path, encoding='utf-8', mode='w') as f:
            f.write(json.dumps(self.book_info_dict))

    def get_insert_book_sql(self) -> str:
        book_info_dict = self.get_book_info_dict()
        field_sql = "insert into book_info ("
        value_sql = " values("
        for field_name in book_info_dict.keys():
            field_value = book_info_dict[field_name]
            if field_value is not None:
                field_sql += field_name + ","
                if field_name == 'title':
                    value_sql += "'" + str(field_value).replace("'", "") + "'" + ","
                else:
                    value_sql += "'" + str(field_value).replace("'", "") + "'" + ","
        value_sql = value_sql[:-1]
        field_sql = field_sql[:-1]
        field_sql += ")"
        value_sql += ")"
        return field_sql + value_sql

    def get_update_book_sql(self) -> str:
        book_info_dict = self.get_book_info_dict()
        sql = "update book_info set "
        for field_name in book_info_dict.keys():
            if field_name == "title":
                continue
            field_value = book_info_dict[field_name]
            if field_value is not None:
                sql += "%s = '%s'," % (field_name, field_value)
        sql = sql[:-1]
        sql += " where title = '%s'" % book_info_dict['title']
        return sql

    def generate_markdown_article(self):
        self.content = ""
        self.content += "### 书籍信息\n"
        self.content += "- 书名: " + self.title + "\n"
        if not StringUtil.isNullStr(self.src_title):
            self.content += "- 原作名: " + self.src_title + "\n"
        if not StringUtil.isNullStr(self.author):
            self.content += "- 作者: " + self.author + "\n"
        if self.score is not None and self.eval_number is not None:
            self.content += "- 豆瓣评分: " + str(self.score) + "分(" + str(self.eval_number) + "人评价)\n"
        if not StringUtil.isNullStr(self.tags):
            self.content += "- 标签: " + ';'.join(self.get_category_list()) + "\n"
        if not StringUtil.isNullStr(self.cover_url):
            self.content += "- ![" + self.title + "](" + self.cover_url + ")\n"
        self.content += "\n"
        self.content += "\n"
        if not StringUtil.isNullStr(self.book_intro):
            self.content += "### 内容简介\n"
            self.content += "- " + self.book_intro + "\n"
            self.content += "\n"
            self.content += "\n"
        if not StringUtil.isNullStr(self.author_intro):
            self.content += "### 作者简介\n"
            self.content += "- " + self.author_intro + "\n"
            self.content += "\n"
            self.content += "\n"
        if not StringUtil.isNullStr(self.download_url):
            self.content += "### 下载地址\n"
            download_url_list = list(self.download_url)
            shielding = "删掉中文"
            download_url_list.insert(2, shielding[0])
            download_url_size = len(download_url_list)
            index = 3
            for i in range(1, 4):
                index = random.randint(index, download_url_size - 15) + 1
                download_url_list.insert(index, shielding[i])
                new_download_url = ''.join(download_url_list)
            self.content += "- " + new_download_url
        self.content = StringUtil.check_filter(self.content)
        return self.content


# def load_book_info(path: str) -> BookInfo:
#     book_info_dict = {}
#     if not os.path.exists(path):
#         return BookInfo(book_info_dict)
#     with open(path, encoding='utf-8', mode='r') as file:
#         fr = file.read()
#         book_info_dict = json.loads(fr)
#     return BookInfo(book_info_dict)


def load_book_info_by_title(database: SqliteDataBase, title) -> BookInfo:
    data = database.sql_select('select * from book_info where title = "{}"'.format(title))
    book_info_dict = {}
    if len(data) > 0:
        field_list = database.get_field_list()
        i = 0
        for field_name in field_list:
            book_info_dict[field_name] = data[0][i]
            i += 1
        return BookInfo(book_info_dict)


def load_book_info_by_book_name(database: SqliteDataBase, book_name) -> BookInfo:
    data = database.sql_select('select * from book_info where book_name = "{}" limit 1'.format(book_name))
    book_info_dict = {}
    if len(data) > 0:
        field_list = database.get_field_list()
        i = 0
        for field_name in field_list:
            book_info_dict[field_name] = data[0][i]
            i += 1
        return BookInfo(book_info_dict)
